import threading
from dwebsocket.decorators import accept_websocket
from django.utils.decorators import method_decorator
from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse
from django.views import View
from book_manage.models import AudioBook
from book_manage.models import Chapter
from book_manage.models import Swiper
from listen_book.models import Comment
from listen_book.models import UserInfo
from book_admin import models
import json
import os
import datetime
from django.contrib import auth
from django.core import serializers
from django.db.models import Q
from django.db.models import Avg, Max, Min, Count, Sum
from book_admin.plugin.router import getRouter
import time


# Create your views here.

# Login


class AdminLogin(View):
    def post(self, request):
        param = json.loads(request.body)
        admin = models.Admin.objects.filter(
            username=param['username'], password=param['password'])
        if len(admin) != 0:
            data = {
                'msg': '登录成功',
                'info': serializers.serialize('json', admin)
            }
        else:
            data = {
                'msg': '用户名或密码错误'
            }
        return JsonResponse(data)


# 管理员权限返回路由
class GetRouter(View):
    def post(self, request):
        param = json.loads(request.body)
        admin = models.Admin.objects.filter(username=param['username']).first()
        router = getRouter(admin.adminManage, admin.userManage, admin.vipManage,
                           admin.bookManage, admin.commentManage, admin.swiperManage)

        return JsonResponse(router)


# 获取ChartData
class HomeMessage(View):
    def post(self, request):
        data = {}

        param = json.loads(request.body)
        # 分类数量
        if param['state'] == 0:
            res1 = AudioBook.objects.values(
                'type').annotate(count=Count('type'))
            data = {
                'list': list(res1)
            }
        # // 播放量top10
        elif param['state'] == 1:
            res = AudioBook.objects.values(
                'bookName', 'playCount').order_by('-playCount')[:10]
            data = {
                'list': list(res)
            }
        #  类型喜爱度
        elif param['state'] == 2:
            res = AudioBook.objects.values('type', ).annotate(
                playSum=Avg('playCount')).order_by('-playSum')
            data = {
                'list': list(res)
            }
        # 听书资源数量
        elif param['state'] == 3:
            res = AudioBook.objects.annotate(count=Count('bookId'))
            data = {
                'list': serializers.serialize('json', res)
            }
        # 用户数量
        elif param['state'] == 4:
            res = UserInfo.objects.annotate(count=Count('username'))
            data = {
                'list': serializers.serialize('json', res)
            }
        # 评论数量
        elif param['state'] == 5:
            res = Comment.objects.annotate(count=Count('id'))
            data = {
                'list': serializers.serialize('json', res)
            }
        return JsonResponse(data)


# admin管理
class AdminManage(View):
    def post(self, request):
        param = json.loads(request.body)
        data = {}
        # 获取admin List
        if param['state'] == 0:
            lists = models.Admin.objects.all()
            data = {
                'list': serializers.serialize('json', lists)
            }
        # 修改
        if param['state'] == 1:
            info = param['admin']
            lines = models.Admin.objects.filter(username=info['username']).update(
                password=info['password'], vipManage=info['vipManage'], adminManage=info['adminManage'],
                userManage=info['userManage'], bookManage=info['bookManage'], commentManage=info['commentManage'],
                swiperManage=info['swiperManage'])
            if lines == 1:
                data['msg'] = '修改成功'
            else:
                data['msg'] = '修改失败'
        # 删除
        if param['state'] == 2:
            info = param['admin']
            lines = models.Admin.objects.filter(
                username=info['username']).delete()
            if lines[0] == 1:
                data['msg'] = '删除成功'
            else:
                data['msg'] = '删除失败'
        # 添加
        if param['state'] == 3:
            info = param['admin']
            try:
                lines = models.Admin.objects.create(
                    username=info['username'],
                    position=info['position'],
                    password=info['password'],
                    vipManage=info['vipManage'],
                    adminManage=info['adminManage'],
                    userManage=info['userManage'],
                    bookManage=info['bookManage'],
                    commentManage=info['commentManage'],
                    swiperManage=info['swiperManage'])
                if lines != None:
                    data['msg'] = '添加成功'
                else:
                    data['msg'] = '添加失败'
            except:
                data['msg'] = '用户名重复'

        return JsonResponse(data)


# userManage
class UserManage(View):
    def post(self, request):
        param = json.loads(request.body)
        data = {}
        # 获取user List
        if param['state'] == 0:
            lists = UserInfo.objects.values(
                'username', 'email', 'fun', 'area', 'phone', 'vip', 'sex', 'info', 'birthday', 'date_joined')
            data = {
                'list': list(lists)
            }
        # 修改密码
        if param['state'] == 1:
            user = UserInfo.objects.get(username=param['username'])
            user.set_password(param['psd'])
            lines = user.save()
            data['msg'] = '修改成功'
        # 删除
        if param['state'] == 2:
            lines = UserInfo.objects.filter(
                username=param['username']).delete()

            data['msg'] = '删除成功'

        return JsonResponse(data)


# vipManage
class VipManage(View):
    def post(self, request):
        param = json.loads(request.body)
        data = {}
        # 获取user List
        if param['state'] == 0:
            lists = UserInfo.objects.values(
                'username', 'email', 'vip', 'sex', 'coin', 'coupon').exclude(vip=None)
            data = {
                'list': list(lists)
            }
        if param['state'] == 1:
            lines = UserInfo.objects.filter(
                username=param['username']).update(vip=param['date'])
            if lines == 1:
                data['msg'] = '修改成功'
            else:
                data['msg'] = '修改失败'

        return JsonResponse(data)


# bookManage
class BookManage(View):
    def post(self, request):
        param = json.loads(request.body)
        data = {}
        # 获取book List
        if param['state'] == 0:
            lists = AudioBook.objects.values()
            data = {
                'list': list(lists)
            }
        # 获取chapter
        if param['state'] == 1:
            lists = AudioBook.objects.filter(bookId=param['bookId']).values(
                'chapter__chapterName', 'chapter__chapterId')
            data = {
                'list': list(lists)
            }
        if param['state'] == 2:  # del
            lists = AudioBook.objects.filter(
                bookId=param['bookId']).delete()
            data = {
                'msg': '删除完成'
            }
        # 修改信息
        if param['state'] == 3:
            info = param['book']
            lists = AudioBook.objects.filter(bookId=info['bookId']).update(
                bookInfo=info['bookInfo'], type=info['type'], pay=info['pay'], price=info['price'])
            if lists == 1:
                data['msg'] = '修改成功'
            else:
                data['msg'] = '修改失败'
        # 添加书籍
        if param['state'] == 4:
            info = param['book']
            try:
                lists = AudioBook.objects.create(
                    bookId=info['bookId'], bookName=info['bookName'], anchor=info['anchor'], img=info['img'],
                    bookInfo=info['bookInfo'], type=info['type'], pay=info['pay'], price=info['price'], playCount=0,
                    date=datetime.datetime.today())
                data['msg'] = '添加成功'
            except:
                data['msg'] = '添加失败:可能bookId重复'
        # 删除章节
        if param['state'] == 5:
            lists = Chapter.objects.filter(
                chapterId=param['chapterId']).delete()
            data = {
                'msg': '删除完成'
            }
        # 修改章节
        if param['state'] == 6:
            lists = Chapter.objects.filter(
                chapterId=param['chapterId']).update(chapterName=param['chapterName'])
            if lists == 2:
                data['msg'] = '修改成功'
            else:
                data['msg'] = '修改失败'
        # 添加章节
        if param['state'] == 7:
            try:
                info = param['book']
                book = AudioBook.objects.get(bookId=info['bookId'])
                chapter = Chapter(
                    chapterId=info['chapterId'], chapterName=info['chapterName'])
                chapter.bookId = book
                chapter.save()
                data['msg'] = '添加成功'
            except:
                data['msg'] = '添加失败：书Id可能未在数据库中'

        return JsonResponse(data)


# 评论管理
class CommentManage(View):
    def post(self, request):
        param = json.loads(request.body)
        data = {}
        if param['state'] == 0:
            lists = Comment.objects.values(
                'bookId__bookName', 'user__username', 'comment', 'id', 'date', 'score')
            data = {
                'list': list(lists)
            }
        if param['state'] == 1:
            lists = Comment.objects.filter(id=param['id']).delete()
            data = {
                'msg': '删除完成'
            }
        return JsonResponse(data)


# swiper管理
class SwiperManage(View):
    def post(self, request):
        param = json.loads(request.body)
        data = {}
        if param['state'] == 0:
            lists = Swiper.objects.values(
                'bookId__bookName', 'types', 'image', 'id', 'bookId')
            data = {
                'list': list(lists)
            }
        if param['state'] == 1:
            lists = Swiper.objects.filter(id=param['id']).delete()
            data = {
                'msg': '删除完成'
            }
        if param['state'] == 2:
            info = param['info']
            lists = Swiper.objects.filter(id=info['id']).update(
                types=info['types'], image=info['image'])
            if lists == 1:
                data['msg'] = '修改成功'
            else:
                data['msg'] = '修改失败'

        if param['state'] == 3:
            info = param['info']
            # try:
            book = AudioBook.objects.get(bookId=info['bookId'])
            lists = Swiper(image=info['image'], types=info['types'])
            lists.bookId = book
            lists.save()
            data['msg'] = '添加成功'
            # except:
            #     data['msg'] = '添加失败：书ID不存在'
        return JsonResponse(data)


# 服务端存储每个链接的对象
clients = {}
count = 0
# 建立websocket


@accept_websocket
def websocketLink(request):
    username = request.GET.get('username')
    print(username)
    global count
    lock = threading.RLock()  # rlock线程锁
    if request.is_websocket():
        lock.acquire()
        s = {}
        # 添加链接用户
        if clients.get(username) == None:
            s['cli'] = request.websocket
            clients[username] = s
            count = count + 1
        else:
            s['cli'] = request.websocket
            clients[username] = s

        print(clients)
        print("在线用户人数" + str(count))
        for message in request.websocket:
            print(message)
            # request.websocket.send(message)
            websocketMsg(clients, message)

# 发送消息


def websocketMsg(client, msg):
    import json
    for cli in client:
        print(client[cli]['cli'])
        # 'client客户端 ，msg消息'
        client[cli]['cli'].send(msg)
